import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProForm, { ProFormText, ProFormRadio } from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { Tree, Card, Col, Row, Alert, message } from 'antd';
import { DownOutlined } from '@ant-design/icons';

const treeDataList = [
  {
    id: '1',
    path: '/system',
    name: '系统管理',
    icon: 'crown',
    routes: [
      { id: '1-1', path: 'menu', name: '菜单管理', icon: 'smile', component: './system/menu' },
      { id: '1-2', path: 'role', name: '角色管理', icon: 'smile', component: './system/role' },
      { id: '1-3', path: 'user', name: '用户管理', icon: 'smile', component: './system/user' },
    ],
  },
];

// 树形数据-获取所有的Keys
function allKeysTreeData(data: any, allKeys: any) {
  data.forEach((v: any) => {
    const tmp = { ...v };
    allKeys.push(tmp.id);
    if (tmp.routes) {
      allKeysTreeData(tmp.routes, allKeys);
    }
  });
  return allKeys;
}
const treeDataKeys = allKeysTreeData(treeDataList, []);

// 处理树形数据
function filterAsyncTreeData(data: any) {
  const res: any = [];
  data.forEach((v: any) => {
    const tmp = { ...v };
    if (tmp.routes) {
      tmp.children = filterAsyncTreeData(tmp.routes);
    }
    tmp.key = tmp.id;
    tmp.title = tmp.name;
    tmp.children = tmp.children;
    res.push(tmp);
  });
  return res;
}
const treeData = filterAsyncTreeData(treeDataList);

const Menu: React.FC = () => {
  const menuFormRef = useRef<ProFormInstance>();

  const [checkedKeyList, setCheckedKeyList] = useState<React.Key[]>();
  // const [AllCheckedVisible, setAllCheckedVisible] = useState(false);
  // const [ExpandAllVisible, setExpandAllVisible] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState(treeDataKeys);

  const [menuCheck, setMenuCheck] = useState(false);
  const [menuInfo, setMenuInfo] = useState<API.MenuListItem>();

  // const [rightClickNodeTreeItem,setRightClickNodeTreeItem]=useState({
  //   pageX: "",
  //   pageY: "",
  //   id: "",
  //   categoryName: ""
  // })

  // 菜单权限
  const onSelect = (selectedKeys: React.Key[], info: any) => {
    setMenuCheck(true);
    setMenuInfo(info.selectedNodes[0]);
    const dataInfo = info.selectedNodes[0];
    menuFormRef.current?.setFieldsValue({
      id: dataInfo?.id,
      name: dataInfo?.name,
      title: dataInfo?.title,
      sort: dataInfo?.sort,
      path: dataInfo?.path,
      icon: dataInfo?.icon,
    });
  };
  const onCheck = (checkedKeys: any, info: any) => {
    setCheckedKeyList(checkedKeys);
    console.log(info);

    setMenuCheck(true);
    setMenuInfo(info.node);
    const dataInfo = info.node;
    menuFormRef.current?.setFieldsValue({
      id: dataInfo?.id,
      name: dataInfo?.name,
      title: dataInfo?.title,
      sort: dataInfo?.sort,
      path: dataInfo?.path,
      icon: dataInfo?.icon,
    });
  };

  // // tree列表上右键事件
  // const onRightClick = (e:any) => {
  //   setRightClickNodeTreeItem({
  //     pageX: e.event.pageX,
  //     pageY: e.event.pageY,
  //     id: e.node.props["data-key"],
  //     categoryName: e.node.props["data-title"]
  //   })
  // }

  // // 自定义右键菜单内容
  // const getNodeTreeRightClickMenu = () => {
  //   const { pageX, pageY, id, categoryName } = { ...rightClickNodeTreeItem };
  //   console.log(pageX,pageY);

  //   const tmpStyle = {
  //     'position': "absolute",
  //     'left': `${parseInt(pageX)  - 282}px`,
  //     'top': `${parseInt(pageY) - 250}px`
  //   };
  //   const menu = (
  //     <div style={tmpStyle} className="self-right-menu">
  //       <a onClick={()=>{}}>新增</a>
  //       <a onClick={()=>{}}>修改</a>
  //       <a>删除目录</a>
  //     </div>
  //   );
  //   return rightClickNodeTreeItem == null ? "" : menu;
  // };

  return (
    <PageContainer title="菜单管理">
      <Row gutter={24}>
        <Col span={12}>
          <Card title="菜单列表" bordered={false} style={{ width: '100%' }}>
            <Tree
              switcherIcon={<DownOutlined />}
              expandedKeys={expandedKeys}
              checkStrictly={true}
              checkable
              checkedKeys={checkedKeyList}
              onSelect={onSelect}
              onCheck={onCheck}
              treeData={treeData}
              onExpand={(Keys, { expanded }) => {
                // setExpandAllVisible(expanded);
                setExpandedKeys(Keys);
              }}
              // onRightClick={onRightClick}
            />
            {/* {getNodeTreeRightClickMenu()} */}
          </Card>
        </Col>

        <Col span={12}>
          <Card
            title={menuInfo?.title ? `编辑菜单 - ${menuInfo.title}` : '编辑菜单'}
            bordered={false}
            style={{ width: '100%' }}
          >
            {!menuCheck && (
              <div style={{ paddingBottom: '20px' }}>
                <Alert message="从菜单列表选择一项（或者右键）后，进行编辑；右键还可删除和添加菜单！" />
              </div>
            )}

            {/* {menuCheck && ( */}
            <ProForm<API.MenuListItem>
              formRef={menuFormRef}
              layout="horizontal"
              onFinish={async (values) => {
                console.log(values);
                message.success('提交成功');
              }}
              params={{}}
            >
              <ProFormText name="title" label="菜单标题" placeholder="请输入菜单标题" />
              <ProFormText name="sort" label="菜单排序" placeholder="请输入菜单排序" />
              <ProFormRadio.Group
                label="菜单类型"
                name="menuType"
                initialValue="1"
                options={[
                  {
                    label: '菜单',
                    value: '1',
                  },
                  {
                    label: '按钮',
                    value: '2',
                  },
                ]}
              />
              <ProFormText name="path" label="菜单路径" placeholder="请输入菜单路径" />
              <ProFormText name="icon" label="菜单图标" placeholder="请输入菜单图标" />
            </ProForm>
            {/* )} */}
          </Card>
        </Col>
      </Row>
    </PageContainer>
  );
};

export default Menu;
